let activeEffect = null;
const targetMap = new WeakMap(); // 存储依赖关系 targetMap:weakMap<target, Map<key, Set<effect>>>

function effect(fn) {
    const effectFn = () => {
        activeEffect = effectFn;
       return fn();
    };
    effectFn();
    return effectFn;
}

function track(target, key) {
    if (!activeEffect) return;
    let depsMap = targetMap.get(target);
    if (!depsMap) {
        targetMap.set(target, (depsMap = new Map()));
    }
    let dep = depsMap.get(key);
    if (!dep) {
        depsMap.set(key, (dep = new Set()));
    }
    dep.add(activeEffect);
    console.log("收集依赖", activeEffect.name);
}

function trigger(target, key) {
    console.log("派发更新");
    let depsMap = targetMap.get(target);
    if (!depsMap) return;
    let dep = depsMap.get(key);
    if (!dep) return;
    // 不考虑循环依赖
    dep.forEach((effectFn) => {
        effectFn();
    });
}

function reactive(target) {
    const handler = {
        get(target, key, receiver) {
            console.log("读取属性：", key);
            track(target, key);
            return Reflect.get(target, key, receiver);
        },
        set(target, key, value, receiver) {
            console.log("设置属性：", key, value);
            const result = Reflect.set(target, key, value, receiver);
            trigger(target, key);
            return result;
        },
    };
    return new Proxy(target, handler);
}

const state = reactive({
    count: 0,
    user: { name: "张三" },
});

effect(() => {
    console.log("effect1:", state.count);
});
